$(function() {
    $lang.init();
    $page.init('user', $user);
    $user.init();
    $('#from_date').datepicker();
    $('#to_date').datepicker();
    //Tooltip
    $('#username, #email, #pass2').tooltip();
});

var $user = function() {
    var $us = {
        fields: {
            name: 'user_name',
            username: 'user_username',
            email: 'user_email',
            password: 'user_password',
            password_match: "user_password_match",
            user_group: 'user_user_group',
        },
        init: function() {
            this._initDialog()._initEvent();
        },
        _initSearch: function() {
            $('#search_name, #search_username, #search_email,\n\
                #sort_status, #search_join_date_from, #search_join_date_to,\n\
                #search_id_from, #search_id_to').keyup(function() {
                $us.refresh();
            });

            $('#search_is_actived, #search_user_group').change(function() {
                $us.refresh();
            });

            return this;
        },
        _initSort: function() {
            $('.sort').click(function($event) {
                var $column = $(this).attr('id').toString().replace('sort_', '');
                var $object = $(this);
                var $option = {
                    type: 'post',
                    url: $project.siteUrl('user/admincp/index/ajax_sort'),
                    dataType: 'json',
                    data: {column: $column},
                    success: function($response, $status) {
                        if ($response.result) {
                            //Change arrow of column.
                            $us.resetSort();
                            if (!$response.data.type_sort) {
                                $('#sort_join_date').parent().addClass('sortdesc');
                            }
                            else {
                                $object.parent().addClass('sort' + $response.data.type_sort);
                            }
                            //Get current page....
                            var $curPage = $('#current_page_product').text();
                            $curPage = !$curPage ? 1 : $curPage;
                            $us.getList($curPage);
                        }
                    }
                };

                $project.ajax($option);
            });

            return this;
        },
        _initDialog: function() {
            //Initialzie datepicker for search.
            $('input.date').datepicker({
                onSelect: function($date) {
                    $us.refresh();
                },
                dateFormat: 'yy-mm-dd'
            });

            return this;
        },
        _initEvent: function() {
            $('input.add').click(function() {
                $dialog.container({
                    title: 'Add user',
                    body: $project.removeComment($('#dlg_add_user').html()),
                    buttons: {
                        Add: function() {
                            $us.add();
                        },
                        Reset: function() {
                            $('#form_add').get(0).reset();
                        },
                        Cancel: function() {
                            $dialog.close().destroy();
                        }
                    }
                });
            });

            //Check all product...
            $('input#all_item').click(function() {
                $('.item-select').prop('checked', this.checked);
            });

            //Delete multiple item...
            $('input#delete_item').click(function() {
                $us.resetDeletedItems().showDeletedItems();
            });

            //Edit a item
            $('.edit-item').live('click', function($event) {
                $event.preventDefault();
                var $id = $(this).prop('id')
                        .toString()
                        .replace('edit_item_', '');

                $user.getById($id);
            });

            //Intialize search and sort event.
            this._initSearch()._initSort();
            return this;
        },
        refresh: function() {
            $page.get(0);
        },
        resetSort: function() {
            $('.sort').parent()
                    .removeClass('sortdesc')
                    .removeClass('sortasc');
        },
        proccessErrorAdd: function($aError) {
            $user.resetFieldAdd();

            for ($error in $aError) {
                $('#' + $user.fields[$error])
                        .after($aError[$error])
                        .css('border', '1px solid red');

                if (!$aError[$error]) {
                    $('#' + $user.fields[$error]).css('border', '');
                }

                //Check if password match is match
                if ($error == 'password_match'){
                    if (!$aError[$error]) {
                        ///////////////////
                        $('#password_match').empty().html('yes');
                    }
                    else {
                        $('#password_match').empty().html('no');
                    }
                }
            }

            //////////////////////////
            $dialog.message({text: 'Please fill the field in red'});
        },
        resetFieldAdd: function() {
            $('.error-message').empty();

            for ($field in $user.fields) {
                $('#' + $user.fields[$field]).css('border', '');
                $('#' + $user.fields[$field] + '+ div.error').remove('div.error');
            }
        },
        resetUploadImage: function() {
            $('div.upload-image-product + div.error').remove('div.error');
        },
        resetUploadImgInput: function() {
            $('#form_image_product').get(0).reset();
            $('div.upload-image-product + div.error').remove('div.error');
        },
        resetFormAdd: function() {
            $('#form_add').get(0).reset();
            $us.resetFieldAdd();
            $('#product_image').val('');
            $('#product_image + img').remove('img');
            $('#product_image + br').remove('br');
            //reset error of image field.
            $('#product_image ~ .error').remove('div');
        },
        add: function() {
            //Set cur_page to input hidden, use for reload page when edit.
            var $curPage = $('#current_page_product').text();
            $('input#product_cur_page').val(!$curPage ? 1 : $curPage);

            var $option = {
                type: 'post',
                url: $('#form_add').attr('action'),
                dataType: 'json',
                data: $('#form_add').serialize(),
                success: function($response, $status) {
                    if ($response.result) {
                        if (!$response.data.cur_page) {
                            location.reload();

                            return;
                        }

                        //In case edit page, reload that page.
                        $dialog.close().destroy();
                        /////////////////////////////
                        $page.get($response.data.cur_page);
                    }
                    else {
                        $user.proccessErrorAdd($response.data);
                    }
                }
            };

            $.ajax($option);
        },
        uploadImage: function() {
            $('#form_image_product').ajaxForm({
                success: function($response) {
                    $response = eval('(' + $response + ')');

                    if ($response.result) {
                        $us.createImage($response.data);
                        $us.resetUploadImgInput();

                        return true;
                    }
                    //Reset.
                    $us.resetUploadImage();
                    $('div.upload-image-product').after($response.message);
                }
            });

            return this;
        },
        createImage: function($object) {
            if ($object == '' || $object == 'undefined') {
                return false;
            }

            //Remove image append the previous time.
            $('#product_image').siblings('img').remove('img');
            //Append new image.
            $('#product_image')
                    .val($object.file_name)
                    .after("<img src='" + $object.obsolute_path_new_image + "' height='100px' width='100px' alt='' /><br />");

            return true;
        },
        getList: function($offset) {
            $page.get($offset);

            return this;
        },
        getSearchObject: function() {
            return $('#form_search').serialize();
        },
        createList: function($productDataList) {
            var $data = $productDataList;
            var $body = $('#body_list');
            $body.empty();

            //Check if no post in table product.
            $('#no_row').remove();

            if (!$data) {
                $body.append('<tr id="no_row" class="no-row"><td colspan="11">' + $lang.phrases.no_product + '</td></tr>');
            }

            //Traverse list product
            for (var $i = 0; $i < $data.length; $i++) {
                var $list = '';
                var $row = $data[$i];
                var $productId = null;

                for (var $col in $row) {
                    if ($col == 'id') {
                        $productId = $row[$col];
                    }

                    $list = this.fillData($col, $row[$col], $list);
                }

                $body.append($list);

                if ($i % 2) {
                    $('#row_' + $productId).addClass('even');
                }
                else {
                    $('#row_' + $productId).addClass('odd');
                }
            }
        },
        fillData: function($col, $data, $list) {
            var $tr = $('#row_user').html();
            $tr = $tr.replace(/^(<\!\-\-)|(\-\-\>)$/, '');
            if ($list) {
                $tr = $list
            }

            switch ($col) {
                case 'id':
                    $tr = $tr.replace(/{user_id}/g, $data);
                    break;
                case 'name':
                    $tr = $tr.replace(/{user_name}/g, $data);
                    break;
                case 'email':
                    $tr = $tr.replace(/{user_email}/g, $data);
                    break;
                case 'username':
                    $tr = $tr.replace(/{user_username}/g, $data);
                    break;
                case 'actived':
                    $tr = $tr.replace(/{user_status}/g, ($data == 1) ? 'active' : 'inactive');
                    break;
                case 'user_group':
                    $tr = $tr.replace(/{user_user_group}/g, $data);
                    break;
                default:
                    $tr = $tr.replace(/{user_join_date}/g, $data);
                    break;
            }
            return $tr;
        },
        deleteProducts: function() {
            var $class = $('.item-select');
            var $ids = '{';

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $ids += '"' + $item + '":"' + $class[$item].id + '",';
                }
            }

            $ids = $ids.replace(/,$/g, '') + '}';
            /////////////////
            var $curPage = $('#current_page_product').text();
            $curPage = !$curPage ? 1 : $curPage;

            var $option = {
                type: 'post',
                url: $project.siteUrl('user/admincp/index/ajax_delete'),
                dataType: 'json',
                data: {item_ids: $ids, cur_page: $curPage},
                success: function($response, $status) {
                    if ($response.result) {
                        //Get list product of page.
                        ///////////////////////////
                        $page.get($response.data.page);
                    }
                }
            };

            $project.ajax($option);
            return this;
        },
        showDeletedItems: function() {
            var $class = $('.item-select');
            var $listDeleted = '';
            var $hasDelItem = false;

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $hasDelItem = true;
                    $listDeleted += '<li class="deleted-item">' + $('#item_name_' + $class[$item].id).text() + '</li>';
                }
            }

            $listDeleted = '<ol>' + $listDeleted + '</ol>';
            //if no item is deleted that isn't show dialog.
            if ($hasDelItem) {
                //Show dialog delete item.
                $dialog.confirmExt(
                        function() {
                            $us.deleteProducts();
                        }, $listDeleted, 'Are you sure to delete these user(s)?');
            }

            return this;
        },
        resetDeletedItems: function() {
            //Append to section deleted product dialog.
            $('#list_deleted_item').empty();
            return this;
        },
        getById: function($id) {
            var $option = {
                type: 'post',
                url: $project.siteUrl('user/admincp/index/ajax_get'),
                dataType: 'json',
                data: {item_id: $id},
                success: function($response, $status) {
                    if ($response.result) {
                        //populate product into edit form. and set useful.
                        $user.populate($response.data);
                    }
                }
            };

            $project.ajax($option);
            return this;
        },
        populate: function($data) {
            $dialog.container({
                title: 'Edit user',
                body: $project.removeComment($('#dlg_add_user').html()),
                buttons: {
                    Add: function() {
                        $us.add();
                    },
                    Reset: function() {
                        $('#form_add').get(0).reset();
                    },
                    Cancel: function() {
                        $dialog.close().destroy();
                    }
                }
            });
            //Set id to edit.
            $('#' + 'user_id').val($data.id);
            //
            $('#' + this.fields.name).val($data.name);
            $('#' + this.fields.username).val($data.username);
            $('#' + this.fields.email).val($data.email);
//            $('#' + this.fields.password).val($data.password);
//            $('#' + this.fields.password_match).val($data.password);
            //Combobox
            $('#' + this.fields.user_group + ' option[value=' + $data.user_group_id + ']').prop('selected', true);
            //Radio button.
            $('#status_' + $data.actived + '[value=' + $data.actived + ']').prop('checked', true);
            //Change action from add to edit.
            $('#form_add').attr('action', $project.siteUrl('user/admincp/index/ajax_save'));

            return this;
        }
    }

    return $us;
}();